package com.px.user.controller;

import com.google.common.collect.ImmutableMap;
import com.px.common.core.RespCode;
import com.px.common.core.Response;
import com.px.common.util.JsonUtil;
import com.px.user.entity.*;
import com.px.user.mapper.*;
import com.px.user.model.ActionModel;
import com.px.user.model.AdminOpsCategory;
import com.px.user.model.PagingResp;
import com.px.user.service.AdminOpsService;
import com.px.user.service.AdminService;
import com.px.user.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import io.swagger.annotations.Authorization;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.validation.constraints.Min;
import java.math.BigDecimal;
import java.security.Principal;
import java.sql.Timestamp;
import java.util.Collection;
import java.util.List;

@Slf4j
@Validated
@RestController
@RequestMapping("/admin")
@Api(value = "管理员信息管理", tags = {"管理员信息管理"})
public class AdminController {

    @Autowired
    private RewardMapper rewardMapper;

    @Autowired
    private ConstTMapper constTMapper;

    @Autowired
    private RolesPaging rolesPaging;

    @Autowired
    private RolesMapper rolesMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private UserService userService;

    @Autowired
    private RoomMapper roomMapper;

    @Autowired
    private ChatRobotMapper chatRobotMapper;

    @Autowired
    private CourseMapper courseMapper;

    @Autowired
    private IPBlackMapper ipBlackMapper;

    @Autowired
    private AdminService adminService;

    @Autowired
    private HttpServletRequest httpServletRequest;

    @Autowired
    private AdminOpsService adminOpsService;

    /**
     * 礼物管理
     *
     * @param reward
     * @return
     */
    @PostMapping("/reward")
    @PreAuthorize("hasAnyAuthority('ADMIN','CHILDADMIN')")
    @ApiOperation(value = "礼物创建", authorizations = {@Authorization(value = "token")}, tags = {"礼物", "总管"})
    public Response rewardPost(@Validated(ActionModel.Insert.class) @RequestBody Reward reward, Authentication authentication) {
        rewardMapper.insert(reward);

        AdminOps adminOps = AdminOps.builder()
                .category(AdminOpsCategory.CREATE_REWARD.getStatus())
                .remark(AdminOpsCategory.CREATE_REWARD.getMsg())
                .url(httpServletRequest.getRequestURI())
                .value(reward.getId().toString())
                .build();
        adminOpsService.setRole(adminOps, authentication);
        adminOpsService.insert(adminOps);
        return Response.success(null);
    }

    @PutMapping("/reward")
    @PreAuthorize("hasAnyAuthority('ADMIN','CHILDADMIN')")
    @ApiOperation(value = "礼物更新", authorizations = {@Authorization(value = "token")}, tags = {"礼物", "总管"})
    public Response rewardPut(@Validated(ActionModel.Update.class) @RequestBody Reward reward, Authentication authentication) {
        rewardMapper.update(reward);

        AdminOps adminOps = AdminOps.builder()
                .category(AdminOpsCategory.UPDATE_REWARD.getStatus())
                .remark(AdminOpsCategory.UPDATE_REWARD.getMsg())
                .url(httpServletRequest.getRequestURI())
                .value(reward.getId().toString())
                .build();
        adminOpsService.setRole(adminOps, authentication);
        adminOpsService.insert(adminOps);

        return Response.success(null);
    }

    @DeleteMapping("/reward/{id}")
    @PreAuthorize("hasAnyAuthority('ADMIN','CHILDADMIN')")
    @ApiOperation(value = "管理员-礼物删除", authorizations = {@Authorization(value = "token")}, tags = {"礼物", "总管"})
    public Response rewardDelete(@ApiParam(value = "礼物ID", example = "4") @PathVariable("id") Long id, Authentication authentication) {
        rewardMapper.delete(id);

        AdminOps adminOps = AdminOps.builder()
                .category(AdminOpsCategory.DELETE_REWARD.getStatus())
                .remark(AdminOpsCategory.DELETE_REWARD.getMsg())
                .url(httpServletRequest.getRequestURI())
                .value(id.toString())
                .build();
        adminOpsService.setRole(adminOps, authentication);
        adminOpsService.insert(adminOps);

        return Response.success(null);
    }

    @PostMapping("/const")
    @PreAuthorize("hasAnyAuthority('ADMIN','CHILDADMIN')")
    @ApiOperation(value = "常量创建", authorizations = {@Authorization(value = "token")}, tags = {"常量", "总管"})
    public Response constPost(@Validated(ActionModel.Insert.class) @RequestBody ConstT constT, Authentication authentication) {
        constTMapper.insert(constT);

        AdminOps adminOps = AdminOps.builder()
                .category(AdminOpsCategory.CREATE_CONST.getStatus())
                .remark(AdminOpsCategory.CREATE_CONST.getMsg())
                .url(httpServletRequest.getRequestURI())
                .value(constT.getId().toString())
                .build();
        adminOpsService.setRole(adminOps, authentication);
        adminOpsService.insert(adminOps);

        return Response.success(null);
    }

    @GetMapping("/const")
    @PreAuthorize("hasAnyAuthority('ADMIN','CHILDADMIN')")
    @ApiOperation(value = "常量获取", authorizations = {@Authorization(value = "token")}, tags = {"常量", "总管"})
    public Response<List<ConstT>> constGet() {
        return Response.success(constTMapper.findAll());
    }

    @PutMapping("/const")
    @PreAuthorize("hasAnyAuthority('ADMIN','CHILDADMIN')")
    @ApiOperation(value = "常量修改", authorizations = {@Authorization(value = "token")}, tags = {"常量", "总管"})
    public Response constPut(@Validated(ActionModel.Update.class) @RequestBody ConstT constT, Authentication authentication) {
        constTMapper.update(constT);

        AdminOps adminOps = AdminOps.builder()
                .category(AdminOpsCategory.UPDATE_CONST.getStatus())
                .remark(AdminOpsCategory.UPDATE_CONST.getMsg())
                .url(httpServletRequest.getRequestURI())
                .value(constT.getId().toString())
                .build();
        adminOpsService.setRole(adminOps, authentication);
        adminOpsService.insert(adminOps);

        return Response.success(null);
    }

    @GetMapping("/const/{id}")
    @PreAuthorize("hasAnyAuthority('ADMIN','CHILDADMIN')")
    @ApiOperation(value = "常量详情", authorizations = {@Authorization(value = "token")}, tags = {"常量", "总管"})
    public Response<ConstT> constOneGet(@ApiParam(value = "常量ID", example = "4") @PathVariable("id") Long id) {
        return Response.success(constTMapper.findById(id));
    }

    @DeleteMapping("/const/{id}")
    @PreAuthorize("hasAnyAuthority('ADMIN','CHILDADMIN')")
    @ApiOperation(value = "常量删除", authorizations = {@Authorization(value = "token")}, tags = {"常量", "总管"})
    public Response<ConstT> constDelete(@ApiParam(value = "常量ID", example = "4") @PathVariable("id") Long id, Authentication authentication) {
        constTMapper.delete(id);

        AdminOps adminOps = AdminOps.builder()
                .category(AdminOpsCategory.DELETE_CONST.getStatus())
                .remark(AdminOpsCategory.DELETE_CONST.getMsg())
                .url(httpServletRequest.getRequestURI())
                .value(id.toString())
                .build();
        adminOpsService.setRole(adminOps, authentication);
        adminOpsService.insert(adminOps);

        return Response.success(null);
    }

    @PostMapping("/role")
    @PreAuthorize("hasAnyAuthority('ADMIN','CHILDADMIN')")
    @ApiOperation(value = "新增角色", authorizations = {@Authorization(value = "token")}, tags = {"角色", "总管"})
    public Response<Long> rolePost(@Validated(ActionModel.Insert.class) @RequestBody Roles role, Authentication authentication) {
        role.setId(null);
        rolesPaging.save(role);

        AdminOps adminOps = AdminOps.builder()
                .category(AdminOpsCategory.CREATE_ROLE.getStatus())
                .remark(AdminOpsCategory.CREATE_ROLE.getMsg())
                .url(httpServletRequest.getRequestURI())
                .value(role.getId().toString())
                .build();
        adminOpsService.setRole(adminOps, authentication);
        adminOpsService.insert(adminOps);

        return Response.success(role.getId());
    }

    @GetMapping("/role")
    @PreAuthorize("hasAnyAuthority('ADMIN','CHILDADMIN')")
    @ApiOperation(value = "角色列表", authorizations = {@Authorization(value = "token")}, tags = {"角色", "总管"})
    public Response<List<Roles>> roleGet() {
        return Response.success(rolesMapper.findAll());
    }

    // TODO 重构
    @PutMapping("/role/{id}")
    @PreAuthorize("hasAnyAuthority('ADMIN','CHILDADMIN')")
    @ApiOperation(value = "角色更新", authorizations = {@Authorization(value = "token")}, tags = {"角色"})
    public Response rolePut(@ApiParam(value = "角色ID", example = "2") @PathVariable("id") Long id,
                            @RequestBody Roles role, Authentication authentication) {
        role.setId(id);
        rolesMapper.update(role);

        AdminOps adminOps = AdminOps.builder()
                .category(AdminOpsCategory.UPDATE_ROLE.getStatus())
                .remark(AdminOpsCategory.UPDATE_ROLE.getMsg())
                .url(httpServletRequest.getRequestURI())
                .value(role.getId().toString())
                .build();
        adminOpsService.setRole(adminOps, authentication);
        adminOpsService.insert(adminOps);

        return Response.success(null);
    }

    @DeleteMapping("/role/{id}")
    @PreAuthorize("hasAnyAuthority('ADMIN','CHILDADMIN')")
    @ApiOperation(value = "角色删除", authorizations = {@Authorization(value = "token")}, tags = {"角色", "总管"})
    public Response roleDelete(@ApiParam(value = "角色ID", example = "2") @PathVariable("id") Long id, Authentication authentication) {
        rolesMapper.delete(id);

        AdminOps adminOps = AdminOps.builder()
                .category(AdminOpsCategory.DELETE_ROLE.getStatus())
                .remark(AdminOpsCategory.DELETE_ROLE.getMsg())
                .url(httpServletRequest.getRequestURI())
                .value(id.toString())
                .build();
        adminOpsService.setRole(adminOps, authentication);
        adminOpsService.insert(adminOps);

        return Response.success(null);
    }

    /**
     * 用户管理
     *
     * @param user
     * @param principal
     * @return
     */
    @PostMapping("/user")
    @PreAuthorize("hasAnyAuthority('ADMIN','CHILDADMIN')")
    @ApiOperation(value = "创建用户", authorizations = {@Authorization(value = "token")}, tags = {"总管", "用户"})
    public Response<Long> userPost(
            @Validated(ActionModel.Insert.class) @RequestBody User user, Principal principal, Authentication authentication) {
        if (user.getDisabled() == null)
            user.setDisabled(0);
        user.setPassword(user.passwordEncode(user.getPassword()));
        user.setRoles(user.roles2json(user.getRoles()));
        user.setSource("Admin-" + principal.getName());
        user.setMoney(BigDecimal.valueOf(0));
        userMapper.insert(user);

        AdminOps adminOps = AdminOps.builder()
                .category(AdminOpsCategory.CREATE_USER.getStatus())
                .remark(AdminOpsCategory.CREATE_USER.getMsg())
                .url(httpServletRequest.getRequestURI())
                .value(user.getId().toString())
                .build();
        adminOpsService.setRole(adminOps, authentication);
        adminOpsService.insert(adminOps);

        return Response.success(user.getId());
    }

    @GetMapping("/user/{id}")
    @PreAuthorize("hasAnyAuthority('ADMIN','CHILDADMIN')")
    @ApiOperation(value = "用户详情", authorizations = {@Authorization(value = "token")}, tags = {"总管", "用户"})
    public Response<User> userGet(@ApiParam(value = "用户ID", example = "4") @PathVariable("id") Long id) {

        User user = userMapper.findById(id);
        if (user != null) {
            user.setRoles(user.json2roles(user.getRoles()));
            return Response.success(user);
        } else
            return Response.fail(RespCode.ACCOUNT_NOT_EXIST, null);
    }

    @GetMapping("/user/search")
    @PreAuthorize("hasAnyAuthority('ADMIN','CHILDADMIN')")
    @ApiOperation(value = "搜索用户", authorizations = {@Authorization(value = "token")}, tags = {"总管", "用户"})
    public Response<PagingResp<User>> userSearchGet(
            @ApiParam(value = "用户ID(管理员使用)") @RequestParam(value = "id", required = false) Long id,
            @ApiParam(value = "是机器人(管理员使用)") @RequestParam(value = "isRobot", required = false) Integer isRobot,
            @ApiParam(value = "是虚拟人(管理员使用)") @RequestParam(value = "isVirtual", required = false) Integer isVirtual,
            @ApiParam(value = "禁用(管理员使用)") @RequestParam(value = "disabled", required = false) Integer disabled,
            @ApiParam(value = "开始时间", example = "1566805792293") @RequestParam(value = "qstart", required = false) Long qstart,
            @ApiParam(value = "截止时间") @RequestParam(value = "qend", required = false) Long qend,
            @ApiParam(value = "角色", example = "ROOMADMIN") @RequestParam(value = "role", required = false) String role,
            @ApiParam(value = "电话(模糊匹配)") @RequestParam(value = "username", required = false) String username,
            @ApiParam(value = "昵称(模糊匹配)", example = "饱饱") @RequestParam(value = "nickname", required = false) String nickname,
            @ApiParam(value = "排序字段(倒序)", example = "updateTime") @RequestParam(value = "orderField", required = false, defaultValue = "createTime") String orderField,
            @ApiParam(value = "页码", example = "0") @RequestParam(value = "page", required = false, defaultValue = "0") @Min(0) Integer page,
            @ApiParam(value = "返回数量", example = "10") @RequestParam(value = "limit", required = false, defaultValue = "10") @Min(1) Integer limit) {
        User qUser = User.builder()
                .id(id)
                .qrole(role)
                .isRobot(isRobot)
                .isVirtual(isVirtual)
                .disabled(disabled)
                .qstart(qstart == null ? null : new Timestamp(qstart))
                .qend(qend == null ? null : new Timestamp(qend))
                .username(username == null ? null : String.join(username, "%", "%"))
                .nickname(nickname == null ? null : String.join(nickname, "%", "%"))
                .orderField(orderField)
                .startIndex(page * limit)
                .limit(limit)
                .build();

        List<User> users = userMapper.paging(qUser);
        users.forEach(item -> item.setRoles(item.json2roles(item.getRoles())));
        return Response.success(PagingResp.<User>builder()
                .itemCount(userMapper.pagingCount(qUser))
                .items(users)
                .build());
    }

    @PutMapping("/user")
    @PreAuthorize("hasAnyAuthority('ADMIN','CHILDADMIN')")
    @ApiOperation(value = "更新用户详情", authorizations = {@Authorization(value = "token")}, notes = "不能修改金额，仅总管使用", tags = {"总管", "用户"})
    public Response userPut(@Validated(ActionModel.Update.class) @RequestBody User user, Principal principal, Authentication authentication) {
        if (StringUtils.isNotEmpty(user.getRoles()))
            user.setRoles(user.roles2json(user.getRoles()));
        if (StringUtils.isNotEmpty(user.getPassword()))
            user.setPassword(user.passwordEncode(user.getPassword()));
        user.setMoney(null);
        if (user.getDisabled() != null && user.getDisabled() == 1)
            userService.invokeToken(user.getId());
        userMapper.update(user);
        log.info(principal.getName() + " update user info: " + JsonUtil.toJson(user));

        AdminOps adminOps = AdminOps.builder()
                .category(AdminOpsCategory.UPDATE_USER.getStatus())
                .remark(AdminOpsCategory.UPDATE_USER.getMsg())
                .url(httpServletRequest.getRequestURI())
                .value(user.getId().toString())
                .build();
        adminOpsService.setRole(adminOps, authentication);
        adminOpsService.insert(adminOps);

        return Response.success(null);
    }

    @PutMapping("/user/disable")
    @PreAuthorize("hasAnyAuthority('ROOMADMIN','CHILDADMIN')")
    @ApiOperation(value = "禁用用户", authorizations = {@Authorization(value = "token")}, notes = "仅房管使用", tags = {"房管", "用户"})
    public Response userDisablePut(@RequestBody User user, Principal principal, Authentication authentication) {
        if (userMapper.disableCheck(ImmutableMap.of("adminId", principal.getName(), "userId", user.getId())) == null)
            return Response.fail(RespCode.USER_NOT_EXIST, null);

        userMapper.updateDisable(user);
        userService.invokeToken(user.getId());

        AdminOps adminOps = AdminOps.builder()
                .category(AdminOpsCategory.DISABLE_USER.getStatus())
                .remark(AdminOpsCategory.DISABLE_USER.getMsg())
                .url(httpServletRequest.getRequestURI())
                .value(user.getId().toString())
                .build();
        adminOpsService.setRole(adminOps, authentication);
        adminOpsService.insert(adminOps);

        return Response.success(null);
    }


    @DeleteMapping("/user/{id}")
    @PreAuthorize("hasAnyAuthority('ADMIN','CHILDADMIN')")
    @ApiOperation(value = "管理员-删除用户", authorizations = {@Authorization(value = "token")}, tags = {"总管", "用户"})
    public Response userDelete(@ApiParam(value = "用户ID", example = "4") @PathVariable("id") Long id, Principal principal, Authentication authentication) {
        log.info(principal.getName() + " remove userId: " + id);
        userMapper.delete(id);

        AdminOps adminOps = AdminOps.builder()
                .category(AdminOpsCategory.DELETE_USER.getStatus())
                .remark(AdminOpsCategory.DELETE_USER.getMsg())
                .url(httpServletRequest.getRequestURI())
                .value(id.toString())
                .build();
        adminOpsService.setRole(adminOps, authentication);
        adminOpsService.insert(adminOps);

        return Response.success(null);
    }

    /**
     * 头像管理
     *
     * @param avatar
     * @return
     */
    @PutMapping("/avatar")
    @PreAuthorize("hasAnyAuthority('ADMIN','CHILDADMIN')")
    @ApiOperation(value = "头像更新", authorizations = {@Authorization(value = "token")}, tags = {"头像"})
    public Response avatarPut(@Validated(ActionModel.Insert.class) @RequestBody Avatar avatar, Authentication authentication) {
        if (avatar.getId() == null)
            return Response.fail(RespCode.PARA_ERROR, null);

        userMapper.updateAvatarById(avatar);

        AdminOps adminOps = AdminOps.builder()
                .category(AdminOpsCategory.UPDATE_AVATAR.getStatus())
                .remark(AdminOpsCategory.UPDATE_AVATAR.getMsg())
                .url(httpServletRequest.getRequestURI())
                .value(avatar.getId().toString())
                .build();
        adminOpsService.setRole(adminOps, authentication);
        adminOpsService.insert(adminOps);

        return Response.success(null);
    }

    @DeleteMapping("/avatar/{id}")
    @PreAuthorize("hasAnyAuthority('ADMIN','CHILDADMIN')")
    @ApiOperation(value = "头像删除", authorizations = {@Authorization(value = "token")}, tags = {"头像"})
    public Response avatarDelete(@ApiParam(value = "头像ID", example = "4") @PathVariable("id") Integer id, Authentication authentication) {
        userMapper.deleteAvatar(id);

        AdminOps adminOps = AdminOps.builder()
                .category(AdminOpsCategory.DELETE_AVATAR.getStatus())
                .remark(AdminOpsCategory.DELETE_AVATAR.getMsg())
                .url(httpServletRequest.getRequestURI())
                .value(id.toString())
                .build();
        adminOpsService.setRole(adminOps, authentication);
        adminOpsService.insert(adminOps);

        return Response.success(null);
    }

    /**
     * 对话管理
     *
     * @param chatRobot
     * @param principal
     * @return
     */
    @PostMapping("/chatRobot")
    @PreAuthorize("hasAnyAuthority('ADMIN','CHILDADMIN')")
    @ApiOperation(value = "对话创建", authorizations = {@Authorization(value = "token")}, tags = {"对话"})
    public Response chatRobotPost(@Validated(ActionModel.Insert.class) @RequestBody ChatRobot chatRobot,
                                  Principal principal, Authentication authentication) {
        chatRobot.setCreatorId(Long.valueOf(principal.getName()));

        AdminOps adminOps = AdminOps.builder()
                .category(AdminOpsCategory.CREATE_CHAT.getStatus())
                .remark(AdminOpsCategory.CREATE_CHAT.getMsg())
                .url(httpServletRequest.getRequestURI())
                .build();
        adminOpsService.setRole(adminOps, authentication);
        adminOpsService.insert(adminOps);

        return adminService.robotNumUpdate(chatRobot);
    }

    @GetMapping("/chatRobot")
    @PreAuthorize("hasAnyAuthority('ADMIN','CHILDADMIN')")
    @ApiOperation(value = "对话搜索", authorizations = {@Authorization(value = "token")}, tags = {"对话"})
    public Response<PagingResp<ChatRobot>> chatRobotGet(
            @ApiParam(value = "id", example = "1") @RequestParam(value = "id", required = false) Integer id,
            @ApiParam(value = "开始时间", example = "1566805792293") @RequestParam(value = "qstart", required = false) Long qstart,
            @ApiParam(value = "截止时间", example = "1566805792293") @RequestParam(value = "qend", required = false) Long qend,
            @ApiParam(value = "类型:random#随机发送,dialogue#对话,interval#间隔时间,robot-num#房间机器人数量", example = "random") @RequestParam(value = "category", required = false) String category,
            @ApiParam(value = "对话匹配(模糊匹配)") @RequestParam(value = "contain", required = false) String contain,
            @ApiParam(value = "对话返回(模糊匹配)") @RequestParam(value = "response", required = false) String response,
            @ApiParam(value = "随机发送(模糊匹配)") @RequestParam(value = "content", required = false) String content,
            @ApiParam(value = "排序字段(倒序)", example = "updateTime") @RequestParam(value = "orderField", required = false, defaultValue = "createTime") String orderField,
            @ApiParam(value = "页码", example = "0") @RequestParam(value = "page", required = false, defaultValue = "0") @Min(0) Integer page,
            @ApiParam(value = "返回数量", example = "10") @RequestParam(value = "limit", required = false, defaultValue = "10") @Min(1) Integer limit) {
        ChatRobot qChatRobot = ChatRobot.builder()
                .id(id)
                .qstart(qstart == null ? null : new Timestamp(qstart))
                .qend(qend == null ? null : new Timestamp(qend))
                .category(category)
                .categoryList(category == null ? null : category.split(","))
                .contain(contain)
                .response(response)
                .content(content)
                .orderField(orderField)
                .startIndex(page * limit)
                .limit(limit)
                .build();

        return Response.success(PagingResp.<ChatRobot>builder()
                .itemCount(chatRobotMapper.pagingCount(qChatRobot))
                .items(chatRobotMapper.paging(qChatRobot))
                .build());
    }

    @PutMapping("/chatRobot")
    @PreAuthorize("hasAnyAuthority('ADMIN','CHILDADMIN')")
    @ApiOperation(value = "对话更新", authorizations = {@Authorization(value = "token")}, tags = {"对话"})
    public Response chatRobotPut(@Validated(ActionModel.Update.class) @RequestBody ChatRobot chatRobot, Authentication authentication) {
        chatRobotMapper.update(chatRobot);

        AdminOps adminOps = AdminOps.builder()
                .category(AdminOpsCategory.UPDATE_CHAT.getStatus())
                .remark(AdminOpsCategory.UPDATE_CHAT.getMsg())
                .url(httpServletRequest.getRequestURI())
                .value(chatRobot.getId().toString())
                .build();
        adminOpsService.setRole(adminOps, authentication);
        adminOpsService.insert(adminOps);

        return Response.success(null);
    }

    @DeleteMapping("/chatRobot/{id}")
    @PreAuthorize("hasAnyAuthority('ADMIN','CHILDADMIN')")
    @ApiOperation(value = "对话删除", authorizations = {@Authorization(value = "token")}, tags = {"对话"})
    public Response chatRobotDelete(@ApiParam(value = "对话ID", example = "2") @PathVariable("id") Integer id,
                                    Authentication authentication) {
        chatRobotMapper.delete(id);

        AdminOps adminOps = AdminOps.builder()
                .category(AdminOpsCategory.DELETE_CHAT.getStatus())
                .remark(AdminOpsCategory.DELETE_CHAT.getMsg())
                .url(httpServletRequest.getRequestURI())
                .value(id.toString())
                .build();
        adminOpsService.setRole(adminOps, authentication);
        adminOpsService.insert(adminOps);

        return Response.success(null);
    }

    /**
     * 跑马灯管理
     *
     * @param principal
     * @return
     */
    @GetMapping("/marquee")
    @PreAuthorize("hasAnyAuthority('ADMIN', 'ROOMADMIN', 'TEACHER')")
    @ApiOperation(value = "跑马灯获取", authorizations = {@Authorization(value = "token")}, tags = {"跑马灯"})
    public Response<List<RoomMarquee>> marqueeGet(Principal principal) {
        return Response.success(roomMapper.findMarqueeByUserId(Long.valueOf(principal.getName())));
    }

    @PostMapping("/marquee")
    @PreAuthorize("hasAnyAuthority('ADMIN', 'ROOMADMIN', 'TEACHER')")
    @ApiOperation(value = "跑马灯创建", authorizations = {@Authorization(value = "token")}, tags = {"跑马灯"})
    public Response marqueePost(@Validated(ActionModel.Insert.class) @RequestBody RoomMarquee roomMarquee,
                                Authentication authentication) {
        String userId = authentication.getName();
        Collection roles = authentication.getAuthorities();
        SimpleGrantedAuthority roomadmin = new SimpleGrantedAuthority("ROOMADMIN");
        SimpleGrantedAuthority teacher = new SimpleGrantedAuthority("TEACHER");
      if (roles.contains(roomadmin)) {
             /*  if (roomMapper.findByAdminId(Room.builder().adminId(Long.valueOf(userId)).build()) == null)
                return Response.fail(RespCode.FORBIDDEN, "非此房间房管"); */
            roomMarquee.setRole("ROOMADMIN");
        } else if (roles.contains(teacher)) {
            if (courseMapper.currentTeacherCheck(
                    ImmutableMap.of("teacherId", userId,
                            "roomId", roomMarquee.getRoomId())) == null)
                return Response.fail(RespCode.FORBIDDEN, "讲师未开课");
            roomMarquee.setRole("TEACHER");
        } else
            roomMarquee.setRole("ADMIN");

        roomMarquee.setId(null);
        roomMarquee.setCreatorId(Long.valueOf(userId));
        roomMapper.insertMarquee(roomMarquee);

        //
//        AdminOps adminOps = AdminOps.builder()
//                .category(AdminOpsCategory.CREATE_MARQUEE.getStatus())
//                .remark(AdminOpsCategory.CREATE_MARQUEE.getMsg())
//                .url(httpServletRequest.getRequestURI())
//                .value(roomMarquee.getId().toString())
//                .build();
//
//        adminOpsService.setRole(adminOps, authentication);
//        adminOpsService.insert(adminOps);

        return Response.success(null);
    }

    @DeleteMapping("/marquee/{id}")
    @PreAuthorize("hasAnyAuthority('ADMIN', 'ROOMADMIN', 'TEACHER')")
    @ApiOperation(value = "跑马灯删除", authorizations = {@Authorization(value = "token")}, tags = {"跑马灯"})
    public Response marqueeDelete(@ApiParam(value = "跑马灯ID", example = "4") @PathVariable("id") Integer id,
                                  Authentication authentication) {

        Collection roles = authentication.getAuthorities();
        SimpleGrantedAuthority admin = new SimpleGrantedAuthority("ADMIN");
        if (roles.contains(admin))
            roomMapper.deleteMarqueeByAdmin(id);
        else
            roomMapper.deleteMarquee(ImmutableMap.of("id", id, "creatorId", authentication.getName()));

        AdminOps adminOps = AdminOps.builder()
                .category(AdminOpsCategory.DELETE_MARQUEE.getStatus())
                .remark(AdminOpsCategory.DELETE_MARQUEE.getMsg())
                .url(httpServletRequest.getRequestURI())
                .value(id.toString())
                .build();
        adminOpsService.setRole(adminOps, authentication);
        adminOpsService.insert(adminOps);

        return Response.success(null);
    }

    @PostMapping("/ipBan")
    @PreAuthorize("hasAnyAuthority('ADMIN','CHILDADMIN')")
    @ApiOperation(value = "IP禁用", authorizations = {@Authorization(value = "token")}, tags = {"IP禁用"})
    public Response ipBanPost(
            @Validated(ActionModel.Insert.class) @RequestBody IPBlack ipBlack,
            Principal principal, Authentication authentication) {
        ipBlack.setCreatorId(Long.valueOf(principal.getName()));
        adminService.iPBan(ipBlack);

        AdminOps adminOps = AdminOps.builder()
                .category(AdminOpsCategory.CREATE_IPBAN.getStatus())
                .remark(AdminOpsCategory.CREATE_IPBAN.getMsg())
                .url(httpServletRequest.getRequestURI())
                .value(ipBlack.getId().toString())
                .build();
        adminOpsService.setRole(adminOps, authentication);
        adminOpsService.insert(adminOps);

        return Response.success(null);
    }

    @GetMapping("/ipBan")
    @PreAuthorize("hasAnyAuthority('ADMIN','CHILDADMIN')")
    @ApiOperation(value = "IP禁用列表", authorizations = {@Authorization(value = "token")}, tags = {"IP禁用"})
    public Response<PagingResp<IPBlack>> ipBanGet(
            @ApiParam(value = "排序字段(倒序)", example = "updateTime") @RequestParam(value = "orderField", required = false, defaultValue = "createTime") String orderField,
            @ApiParam(value = "页码", example = "0") @RequestParam(value = "page", required = false, defaultValue = "0") @Min(0) Integer page,
            @ApiParam(value = "返回数量", example = "10") @RequestParam(value = "limit", required = false, defaultValue = "10") @Min(1) Integer limit) {
        IPBlack qIpBlack = IPBlack.builder().orderField(orderField).startIndex(page * limit).limit(limit).build();
        return Response.success(PagingResp.<IPBlack>builder()
                .itemCount(ipBlackMapper.pagingCount(qIpBlack))
                .items(ipBlackMapper.paging(qIpBlack))
                .build());
    }

    @DeleteMapping("/ipBan/{id}")
    @PreAuthorize("hasAnyAuthority('ADMIN','CHILDADMIN')")
    @ApiOperation(value = "IP禁用删除", authorizations = {@Authorization(value = "token")}, tags = {"IP禁用"})
    public Response ipBanDelete(@ApiParam(value = "id", example = "2") @PathVariable("id") Integer id,
                                Authentication authentication) {
        ipBlackMapper.delete(id);

        AdminOps adminOps = AdminOps.builder()
                .category(AdminOpsCategory.CREATE_IPBAN.getStatus())
                .remark(AdminOpsCategory.CREATE_IPBAN.getMsg())
                .url(httpServletRequest.getRequestURI())
                .value(id.toString())
                .build();
        adminOpsService.setRole(adminOps, authentication);
        adminOpsService.insert(adminOps);

        return Response.success(null);
    }
}
